﻿/*
#------------------------------------------------------------------------------
#-- Program Name:	[dbo].[spMaint_GetDefaultDataDirectory]
#-- Purpose:		Gets the default data directory for the instance.
#--	Last Update:	05/08/2013
#--					For a complete history - please review comments in Version
#--					control.
#-- Required XPs:	[master].[dbo].[xp_instance_regread]
#------------------------------------------------------------------------------
*/
CREATE PROCEDURE [dbo].[spMaint_GetDefaultDataDirectory]
(
	@data_directory_name		varchar(8000)		OUTPUT
)
AS
BEGIN
	--- Determine the base directory for data files
	SELECT	@data_directory_name = CAST(SERVERPROPERTY('InstanceDefaultDataPath') as nvarchar(MAX))
	IF ISNULL(@data_directory_name, '') = ''
	  BEGIN
		EXEC [master].[dbo].[xp_instance_regread] N'HKEY_LOCAL_MACHINE',N'SOFTWARE\Microsoft\MSSQLServer\MSSQLServer', N'DefaultData', @data_directory_name output, ''
		IF ISNULL(@data_directory_name, '') = ''
		  BEGIN
			EXEC [master].[dbo].[xp_instance_regread] N'HKEY_LOCAL_MACHINE',N'SOFTWARE\Microsoft\MSSQLServer\Setup', N'SQLDataRoot', @data_directory_name output, ''
			IF NOT ISNULL(@data_directory_name, '') = ''
				SELECT	@data_directory_name = @data_directory_name + '\Data'
		  END
	  END

	--- A Default Data Directory must exist
	IF ISNULL(@data_directory_name, '') = ''
	  BEGIN
		DECLARE @i int
		SET @i = 'The Default Data Folder was not configured and is required' + 0
		RETURN (-999)
	  END
	ELSE
		SELECT	@data_directory_name = LTRIM(RTRIM(@data_directory_name))
	
	--- Ensure the path ends with a '\' character
	IF NOT RIGHT(@data_directory_name, 1) = '\'
		SELECT @data_directory_name = @data_directory_name + '\'
END
